package com.easy.work.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.pulltorefresh.PullToRefreshBase;
import com.base.syslib.pulltorefresh.PullToRefreshListView;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseFragment;
import com.easy.work.bean.MsgEvent;
import com.easy.work.db.DataProvider;
import com.easy.work.db.MessageBean;
import com.easy.work.function.me.MsgDetailActivity;
import com.easy.work.function.me.adapter.MessageAdapter;
import com.easy.work.function.message.SystemMessageAct;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Admin on 2017/12/6.
 * 消息
 */
public class MessageFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener<ListView> {
    @BindView(R.id.title_txt)
    TextView titleTxt;
    @BindView(R.id.listView)
    PullToRefreshListView refreshListView;
    Unbinder unbinder;
    ListView listView;
    private MessageAdapter mAdapter;

    private boolean isVisible = false;

    private List<MessageBean> mList = new ArrayList<>();

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_message;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {

        View rootView = super.onCreateView(inflater, container, bundle);
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    void initView() {
        Logs.e("JPush", "initView");
        mAdapter = new MessageAdapter(getActivity(), 1, mList, 0);
        refreshListView.setPullLoadEnabled(true);
        refreshListView.setPullRefreshEnabled(true);
        refreshListView.setOnRefreshListener(this);

        listView = refreshListView.getRefreshableView();
        listView.setHeaderDividersEnabled(false);
        listView.setDividerHeight(0);


        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Logs.e("ListView", "position:" + position);
                MessageBean bean = (MessageBean) parent.getAdapter().getItem(position);
                Logs.e("MessageFragment", "type:" + bean.getMsgType());
                if (bean.getMsgType() == 3) {
                    SystemMessageAct.start(getActivity(), bean);
                } else {
                    MsgDetailActivity.start(getActivity(), bean);
                }
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                MessageBean bean = (MessageBean) parent.getAdapter().getItem(position);
//                if (bean.getMsgType() == 3) {
//                    return true;
//                } else {
                showNoticeDialog(bean);
                return true;
//                }
            }
        });

        AppSession.setPullFormartRefreshTime(refreshListView);

    }

    @Override
    public void onResume() {
        super.onResume();
        Logs.e("JPush", "onResume_isVisible:" + isVisible);
        if (isVisible) {
            getLocalData();
        }
    }

    /**
     * 刷新
     */
    public void refresh() {
        if (isVisible) {
            getLocalData();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            Logs.e("JPush", "onHiddenChanged");
            isVisible = true;
            getLocalData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getLocalData();
        refreshListView.onPullUpRefreshComplete();
        refreshListView.onPullDownRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        refreshListView.onPullUpRefreshComplete();
        refreshListView.onPullDownRefreshComplete();
    }

    private void getLocalData() {
//        List<MessageBean> list = new ArrayList<>();
//        int unReadCount = 0;
//        List<MessageBean> unreadSystemList = DataProvider.getSystemMsg(getActivity(), false);
//        if (unreadSystemList != null && !unreadSystemList.isEmpty()) {
////            unReadCount = unreadSystemList.size();
////            list.add(unreadSystemList.get(0));
//            list.addAll(unreadSystemList);
//        } else {
//            List<MessageBean> readSystemList = DataProvider.getSystemMsg(getActivity(), true);
//            if (readSystemList != null && !readSystemList.isEmpty()) {
////                list.add(readSystemList.get(0));
//                list.addAll(readSystemList);
//            }
//        }
//        // 没有系统消息时，默认添加一条
//        if (list.isEmpty()) {
//            list.add(DataProvider.getMsgInstance());
//        }
//
//        List<MessageBean> mxLyList = DataProvider.queryByUserIdAndMxLy(getActivity());
//        if (mxLyList != null && !mxLyList.isEmpty()) {
//            list.addAll(mxLyList);
//        }
//        mAdapter.refresh(list, unReadCount);

        // 读取系统消息
        List<MessageBean> systemList = DataProvider.queryByUserIdAndMsgType(getActivity(), 3);
        List<MessageBean> allMsgList = DataProvider.queryAllByUserId(getActivity());
        if (allMsgList != null && !allMsgList.isEmpty()) {
            for (MessageBean messageBean : allMsgList) {
                Logs.e("Test", "time:" + messageBean.getTime());
            }
            Collections.sort(allMsgList, new Comparator<MessageBean>() {
                @Override
                public int compare(MessageBean o1, MessageBean o2) {
                    return o2.getDate().compareTo(o1.getDate());
                }
            });
        }
        List<MessageBean> list = new ArrayList<>();
        // 没有系统消息时，默认添加一条
        if (systemList == null || systemList.isEmpty()) {
            list.add(DataProvider.getMsgInstance());
        }
        if (allMsgList != null && !allMsgList.isEmpty()) {
            list.addAll(allMsgList);
        }
        mAdapter.refresh(list);
    }

    private void showNoticeDialog(final MessageBean bean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("温馨提示");
        builder.setMessage("确定要删除该条消息吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DataProvider.deleteData(getActivity(), bean);
                mList.remove(bean);
                mAdapter.notifyDataSetChanged();
                if (!bean.getReadState()) {
                    EventBus.getDefault().post(new MsgEvent());
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }
}
